# coding=utf-8
# @File  : objsrv_controller.py.py
# @Author: WUXY
# @Date  : 2019/2/26
# @Desc  :

import requests
import json
from controller.controller_base import *
from flask import current_app


class ObjSrvController(ControllerBase):
    def __init__(self):
        super(ObjSrvController, self).__init__()
        self.OBJ_SRV_CONFIG = current_app.config['OBJ_SRV_CONFIG']

    def login(self):
        url = '%s%s' % (self.OBJ_SRV_CONFIG['GATE'], '/thinkphp/home/user/logininternal')
        data = self.OBJ_SRV_CONFIG['USER_PARAMS']
        r = requests.post(url=url, data=json.dumps(data))
        content = r.content.split('</pre>')[-1]
        content = r and json.loads(content)
        if (not content) or content['retcode'] != 1:
            writelog('url:%s, data:%s' % (url, r.content))
            return False
        return r.cookies

    def get_user_by_cookie(self):
        user_item = {}

        sid = ''
        cookies = self.login()
        for item in cookies.items():
            if item[0] == 'IDREAMSESSID':
                sid = item[1]
                break

        if sid:
            url = '%s%s' % (self.OBJ_SRV_CONFIG['GATE'], '/thinkphp/home/user/getUserIdBySid')
            data = {
                'sid': sid,
                'key': self.OBJ_SRV_CONFIG['USER_PARAMS']['key']
            }
            r = requests.post(url=url, data=json.dumps(data))
            ret = json.loads(r.content)
            if ret.get('retcode') == 1:
                user_item = ret.get('retdata')
        return user_item

    def create_private_world(self, world_name):
        world_item = {}

        user_info = self.get_user_by_cookie()
        user_id = user_info.get('user_id')

        if user_id:
            url = '%s%s' % (self.OBJ_SRV_CONFIG['GATE'], '/thinkphp/home/itemTest/createPrivateWorld')
            data = {
                'userid': user_id,
                'name': world_name,
                'key': self.OBJ_SRV_CONFIG['USER_PARAMS']['key']
            }

            r = requests.post(url=url, data=json.dumps(data))
            ret = json.loads(r.content)

            if ret.get('retcode') == 1:
                world_item = ret.get('retdata')
        return world_item

    def delete_private_world(self, world_id):
        result = False

        url = '%s%s' % (self.OBJ_SRV_CONFIG['GATE'], '/thinkphp/home/itemTest/delGisPrivateWorld')
        data = {
            'id': world_id,
            'key': self.OBJ_SRV_CONFIG['USER_PARAMS']['key']
        }

        r = requests.post(url=url, data=json.dumps(data))
        ret = json.loads(r.content)

        if ret.get('retcode') == 1:
            result = True
        return result

    # 删除gis物体
    def delete_obj(self, global_ids):
        result = False
        try:
            url = '%s%s' % (self.OBJ_SRV_CONFIG['GATE'], '/thinkphp/home/itemTest/s_item_delete')
            post_data = dict()
            post_data['key'] = self.OBJ_SRV_CONFIG['USER_PARAMS']['key']
            post_data['item_req'] = global_ids

            r = requests.post(url=url, data=json.dumps(post_data))
            content = json.loads(r.content)
            if content.get('retcode') == 1:
                result = True
            else:
                writelog('删除GIS物体失败: data=%s, response=%s' % (post_data, r.content))
        except:
            writelog(traceback.format_exc())
        return result

    # 创建物体
    def create_obj(self, data):
        obj_id = ''
        try:
            url = '%s%s' % (self.OBJ_SRV_CONFIG['GATE'], '/thinkphp/home/itemTest/s_item_create')
            data['key'] = self.OBJ_SRV_CONFIG['USER_PARAMS']['key']
            r = requests.post(url=url, data=json.dumps(data))
            content = json.loads(r.content)
            if content.get('retcode') == 1:
                obj_id = content['retdata'][0]['id']
            else:
                writelog('创建物体失败: data=%s, response=%s' % (data, r.content))
        except:
            writelog(traceback.format_exc())
        return obj_id

    # 更新物体
    def update_obj(self, data, cookies):
        result = False
        try:
            url = '%s%s' % (self.OBJ_SRV_CONFIG['GATE'], '/thinkphp/home/itemTest/s_item_update')
            data['key'] = self.OBJ_SRV_CONFIG['USER_PARAMS']['key']
            r = requests.post(url=url, data=json.dumps(data), cookies=cookies)
            content = json.loads(r.content)
            if content.get('retcode') == 1:
                result = True
            else:
                writelog('更新物体失败: data=%s, response=%s' % (data, r.content))
        except:
            writelog(traceback.format_exc())
        return result
